package com.example.prometheuswrite.write;

import com.example.prometheuswrite.prometheus.Remote;
import com.example.prometheuswrite.prometheus.Types;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xerial.snappy.Snappy;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fred
 * @date 2022/7/17 08:4447
 * @description 接口 prometheus remote write data
 */
@RequestMapping
@RestController
public class RemoteController {

    /**
     * 直接 接口 remote write的数据
     * @param body
     * @param request
     * @throws IOException
     * @throws InterruptedException
     */
    @PostMapping(value = "/receive")
    public void write(@RequestBody byte[] body, HttpServletRequest request) throws IOException, InterruptedException {
        //解压缩
        byte[] a = Snappy.uncompress(body);
        //获取内容
        List<Types.TimeSeries> timeSeriesList = Remote.WriteRequest.parseFrom(a).getTimeseriesList();
        for (Types.TimeSeries timeSeries : timeSeriesList) {
            List<Types.Sample> samples = timeSeries.getSamplesList();
            List<Types.Label> labels = timeSeries.getLabelsList();
            Map<String, Object> map = new LinkedHashMap<>();
            for (Types.Label label : labels) {
                map.put(label.getName(), label.getValue());
            }
            for (Types.Sample sample : samples) {
                map.put("timestamp", sample.getTimestamp());
                map.put("value", sample.getValue());
            }
            System.out.println(map);
        }
    }
}
